<template>
  <div class="teacher-dashboard">
    <div class="container">
      <!-- 页面标题和导航 -->
      <div class="dashboard-header">
        <h1>🎯 教师精准教学数据看板</h1>
        <p class="subtitle">学生的学习数据，汇聚成了教师精准教学的罗盘</p>
        
        <div class="controls-section">
          <div class="class-selector">
            <label for="classSelect">选择班级：</label>
            <select id="classSelect" v-model="selectedClass" @change="loadDashboardData">
              <option v-for="i in 17" :key="i" :value="i">{{ i }}班</option>
            </select>
          </div>
          
          <div class="date-selector">
            <label for="dateSelect">选择日期：</label>
            <input 
              type="date" 
              id="dateSelect"
              v-model="selectedDate" 
              @change="loadDashboardData"
              class="date-input"
            >
          </div>
          
          <div class="view-mode">
            <button 
              v-for="mode in viewModes" 
              :key="mode.key"
              @click="currentView = mode.key"
              :class="['view-btn', { active: currentView === mode.key }]"
            >
              {{ mode.icon }} {{ mode.label }}
            </button>
          </div>
        </div>
      </div>
      
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在加载教学数据...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="loadDashboardData" class="btn">重新加载</button>
      </div>
      
      <div v-else-if="dashboardData" class="dashboard-content">
        <!-- 班级整体概览 -->
        <div v-if="currentView === 'overview'" class="overview-section">
          <div class="stats-grid">
            <div class="stat-card primary">
              <div class="stat-icon">👥</div>
              <div class="stat-content">
                <div class="stat-number">{{ dashboardData.total_students }}</div>
                <div class="stat-label">参与学生</div>
                <div class="stat-trend">班级规模</div>
              </div>
            </div>
            
            <div class="stat-card success">
              <div class="stat-icon">📊</div>
              <div class="stat-content">
                <div class="stat-number">{{ dashboardData.average_score }}</div>
                <div class="stat-label">班级平均分</div>
                <div class="stat-trend" :class="getScoreTrendClass(dashboardData.average_score)">{{ getScoreTrend(dashboardData.average_score) }}</div>
              </div>
            </div>
            
            <div class="stat-card warning">
              <div class="stat-icon">⭐</div>
              <div class="stat-content">
                <div class="stat-number">{{ excellentRate }}%</div>
                <div class="stat-label">优秀率</div>
                <div class="stat-trend">≥90分学生比例</div>
              </div>
            </div>
            
            <div class="stat-card info">
              <div class="stat-icon">✅</div>
              <div class="stat-content">
                <div class="stat-number">{{ passRate }}%</div>
                <div class="stat-label">及格率</div>
                <div class="stat-trend">≥60分学生比例</div>
              </div>
            </div>
          </div>
          
          <!-- 分数分布可视化 -->
          <div class="chart-section">
            <h3>📈 班级成绩分布情况</h3>
            <div class="chart-container">
              <canvas ref="scoreDistributionChart" width="400" height="200"></canvas>
            </div>
          </div>
          
          <!-- 知识点掌握热力图 -->
          <div class="knowledge-heatmap">
            <h3>🎯 知识点掌握热力图</h3>
            <div class="heatmap-grid">
              <div 
                v-for="kp in dashboardData.knowledge_point_analysis" 
                :key="kp.knowledge_point"
                class="heatmap-cell"
                :class="getHeatmapClass(kp.accuracy_rate)"
                :title="`${kp.knowledge_point}: ${kp.accuracy_rate}%`"
              >
                <div class="cell-label">{{ kp.knowledge_point }}</div>
                <div class="cell-value">{{ kp.accuracy_rate }}%</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 学生个体分析 -->
        <div v-if="currentView === 'students'" class="students-section">
          <div class="section-header">
            <h3>👨‍🎓 学生个体学习轨迹分析</h3>
            <p>每一位学生的学习轨迹都清晰可见</p>
          </div>
          
          <!-- 学生选择器 -->
          <div class="student-selector-section">
            <h4>🔍 选择学生查看详细轨迹</h4>
            <div class="student-selector">
              <select v-model="selectedStudent" @change="fetchStudentTrajectory">
                <option value="">选择学生</option>
                <option v-for="student in dashboardData.top_performers.concat(dashboardData.need_help_students)" :key="student.student_name" :value="student.student_name">
                  {{ student.student_name }} ({{ student.score }}分)
                </option>
              </select>
            </div>
          </div>
          
          <!-- 学生详细轨迹 -->
          <div v-if="studentTrajectory" class="student-detail">
            <div class="student-overview">
              <div class="overview-card">
                <h4>📊 {{ selectedStudent }} 学习概况</h4>
                <div class="stats-grid">
                  <div class="stat-item">
                    <span class="label">总答题次数</span>
                    <span class="value">{{ studentTrajectory.total_attempts }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">最近成绩</span>
                    <span class="value">{{ studentTrajectory.trajectory[0]?.score || 0 }}分</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">平均正确率</span>
                    <span class="value">{{ calculateAverageAccuracy() }}%</span>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="trajectory-chart">
              <h4>📈 学习轨迹图</h4>
              <canvas ref="trajectoryChart" style="height: 300px;"></canvas>
            </div>
            
            <div class="knowledge-progress">
              <h4>🎯 知识点掌握情况</h4>
              <div v-if="studentTrajectory.trajectory.length > 0" class="knowledge-grid">
                <div v-for="(mastery, kp) in studentTrajectory.trajectory[0].knowledge_point_mastery" :key="kp" class="knowledge-item">
                  <div class="knowledge-header">
                    <span class="knowledge-name">{{ kp }}</span>
                    <span class="knowledge-score" :class="getKnowledgeScoreClass(mastery)">{{ mastery }}%</span>
                  </div>
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{width: mastery + '%', backgroundColor: getProgressColor(mastery)}"></div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="learning-history">
              <h4>📚 答题历史</h4>
              <div class="history-table">
                <table>
                  <thead>
                    <tr>
                      <th>日期</th>
                      <th>时间</th>
                      <th>成绩</th>
                      <th>正确题数</th>
                      <th>总题数</th>
                      <th>正确率</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="record in studentTrajectory.trajectory.slice(0, 10)" :key="record.submission_id">
                      <td>{{ record.date }}</td>
                      <td>{{ record.time }}</td>
                      <td class="score-cell" :class="getScoreClass(record.score)">{{ record.score }}分</td>
                      <td>{{ record.correct_count }}</td>
                      <td>{{ record.total_questions }}</td>
                      <td>{{ Math.round((record.correct_count / record.total_questions) * 100) }}%</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          
          <!-- 优秀学生展示 -->
          <div class="performance-group">
            <h4>🏆 表现优秀的学生</h4>
            <div v-if="dashboardData.top_performers.length > 0" class="student-grid">
              <div 
                v-for="(student, index) in dashboardData.top_performers" 
                :key="student.student_name"
                class="student-card excellent"
                @click="selectedStudent = student.student_name; fetchStudentTrajectory()"
              >
                <div class="student-rank">{{ index + 1 }}</div>
                <div class="student-avatar">{{ student.student_name.charAt(0) }}</div>
                <div class="student-info">
                  <div class="student-name">{{ student.student_name }}</div>
                  <div class="student-metrics">
                    <span class="metric score">{{ student.score }}分</span>
                    <span class="metric accuracy">{{ student.accuracy_rate }}%</span>
                  </div>
                  <div class="submission-time">{{ formatDate(student.submission_time) }}</div>
                </div>
                <div class="performance-badge excellent">优秀</div>
              </div>
            </div>
          </div>
          
          <!-- 需要帮助的学生 -->
          <div class="performance-group">
            <h4>🆘 需要重点关注的学生</h4>
            <div v-if="dashboardData.need_help_students.length > 0" class="student-grid">
              <div 
                v-for="student in dashboardData.need_help_students" 
                :key="student.student_name"
                class="student-card need-help"
                @click="selectedStudent = student.student_name; fetchStudentTrajectory()"
              >
                <div class="student-avatar warning">{{ student.student_name.charAt(0) }}</div>
                <div class="student-info">
                  <div class="student-name">{{ student.student_name }}</div>
                  <div class="student-metrics">
                    <span class="metric score low">{{ student.score }}分</span>
                    <span class="metric accuracy low">{{ student.accuracy_rate }}%</span>
                  </div>
                  <div v-if="student.weak_knowledge_points.length > 0" class="weak-points">
                    <strong>薄弱知识点：</strong>
                    <div class="weak-point-tags">
                      <span v-for="point in student.weak_knowledge_points" :key="point" class="weak-point-tag">
                        {{ point }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="performance-badge warning">需关注</div>
              </div>
            </div>
            <div v-else class="no-data">
              <p>🎉 太棒了！所有学生都达到了及格标准</p>
            </div>
          </div>
        </div>
        
        <!-- 共性问题分析 -->
        <div v-if="currentView === 'errors'" class="errors-section">
          <div class="section-header">
            <h3>🔍 共性错题深度分析</h3>
            <p>错误率最高的共性问题，系统都能精准"画像"</p>
          </div>
          
          <!-- 错题概览 -->
          <div class="error-overview-section">
            <div class="overview-cards">
              <div class="stat-card error-summary">
                <div class="card-icon">📊</div>
                <div class="card-content">
                  <h4>错题总览</h4>
                  <div class="summary-stats">
                    <div class="summary-item">
                      <span class="label">平均错误率</span>
                      <span class="value">{{ getAverageErrorRate() }}%</span>
                    </div>
                    <div class="summary-item">
                      <span class="label">最难知识点错误率</span>
                      <span class="value">{{ getMostDifficultErrorRate() }}%</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="stat-card most-difficult">
                <div class="card-icon">⚠️</div>
                <div class="card-content">
                  <h4>最薄弱知识点</h4>
                  <div class="difficult-question">
                    <p class="question-content">{{ getMostDifficultKnowledgePoint()?.knowledge_point || '暂无数据' }}</p>
                    <div class="question-meta">
                      <span class="error-rate">{{ 100 - (getMostDifficultKnowledgePoint()?.accuracy_rate || 0) }}%</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="stat-card problematic-kp">
                <div class="card-icon">🎯</div>
                <div class="card-content">
                  <h4>需要重点关注</h4>
                  <div class="kp-info">
                    <p class="kp-name">{{ priorityKnowledgePoints.length }}个知识点</p>
                    <div class="kp-stats">
                      <span class="error-count">正确率低于70%</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 错误率排行 -->
          <div class="error-ranking">
            <h4>📉 知识点错误率排行</h4>
            <div class="ranking-list">
              <div 
                v-for="(kp, index) in sortedKnowledgePoints" 
                :key="kp.knowledge_point"
                class="ranking-item"
                :class="getRankingClass(kp.accuracy_rate)"
              >
                <div class="ranking-number">{{ index + 1 }}</div>
                <div class="ranking-content">
                  <div class="ranking-title">{{ kp.knowledge_point }}</div>
                  <div class="ranking-stats">
                    <span class="error-rate">错误率: {{ 100 - kp.accuracy_rate }}%</span>
                    <span class="question-count">涉及题目: {{ kp.total_questions }}道</span>
                    <span class="wrong-count">错误次数: {{ kp.incorrect_count }}次</span>
                  </div>
                  <div v-if="kp.common_wrong_answers && kp.common_wrong_answers.length > 0" class="common-errors">
                    <strong>常见错误选项：</strong>
                    <span v-for="answer in kp.common_wrong_answers" :key="answer" class="error-option">
                      {{ answer }}
                    </span>
                  </div>
                </div>
                <div class="accuracy-indicator" :class="getAccuracyClass(kp.accuracy_rate)">
                  {{ kp.accuracy_rate }}%
                </div>
              </div>
            </div>
          </div>
          
          <!-- 知识点错误分析 -->
          <div class="knowledge-error-section">
            <h4>🧠 知识点错误分析热力图</h4>
            <div class="kp-error-grid">
              <div v-for="kp in dashboardData.knowledge_point_analysis?.slice(0, 8)" :key="kp.knowledge_point" class="kp-error-card">
                <div class="kp-header">
                  <h5>{{ kp.knowledge_point }}</h5>
                  <div class="kp-error-rate" :class="getErrorRateClass(100 - kp.accuracy_rate)">
                    {{ 100 - kp.accuracy_rate }}%
                  </div>
                </div>
                
                <div class="kp-stats">
                  <div class="stat-row">
                    <span class="label">错误次数:</span>
                    <span class="value">{{ kp.incorrect_count }}</span>
                  </div>
                  <div class="stat-row">
                    <span class="label">总答题次数:</span>
                    <span class="value">{{ kp.total_questions }}</span>
                  </div>
                  <div class="stat-row">
                    <span class="label">正确率:</span>
                    <span class="value">{{ kp.accuracy_rate }}%</span>
                  </div>
                </div>
                
                <div class="progress-bar">
                  <div class="progress-fill" :style="{width: (100 - kp.accuracy_rate) + '%', backgroundColor: getErrorProgressColor(100 - kp.accuracy_rate)}"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 教学建议 -->
        <div v-if="currentView === 'suggestions'" class="suggestions-section">
          <div class="section-header">
            <h3>💡 精准教学建议</h3>
            <p>教师依据这些客观数据，进行靶向式讲解，让教学决策从"凭经验"转向"看数据"</p>
            
            <!-- 数据筛选和导出控件 -->
            <div class="filter-export-controls">
              <div class="filter-section">
                <div class="filter-group">
                  <label>📅 时间范围：</label>
                  <select v-model="filterTimeRange" @change="applyFilters">
                    <option value="all">全部时间</option>
                    <option value="today">今天</option>
                    <option value="week">本周</option>
                    <option value="month">本月</option>
                    <option value="custom">自定义</option>
                  </select>
                  <div v-if="filterTimeRange === 'custom'" class="custom-date-range">
                    <input type="date" v-model="customStartDate" @change="applyFilters" placeholder="开始日期">
                    <span>至</span>
                    <input type="date" v-model="customEndDate" @change="applyFilters" placeholder="结束日期">
                  </div>
                </div>
                
                <div class="filter-group">
                  <label>🎓 班级筛选：</label>
                  <select v-model="filterClassRange" @change="applyFilters">
                    <option value="current">当前班级</option>
                    <option value="all">全部班级</option>
                    <option value="multiple">多班级对比</option>
                  </select>
                  <div v-if="filterClassRange === 'multiple'" class="multiple-class-selector">
                    <div v-for="i in 17" :key="i" class="class-checkbox">
                      <input type="checkbox" :id="'class-' + i" v-model="selectedClasses" :value="i">
                      <label :for="'class-' + i">{{ i }}班</label>
                    </div>
                  </div>
                </div>
                
                <div class="filter-group">
                  <label>📚 知识点筛选：</label>
                  <select v-model="filterKnowledgePoint" @change="applyFilters">
                    <option value="all">全部知识点</option>
                    <option value="weak">薄弱知识点</option>
                    <option value="priority">重点关注</option>
                    <option v-for="kp in availableKnowledgePoints" :key="kp" :value="kp">
                      {{ kp }}
                    </option>
                  </select>
                </div>
                
                <div class="filter-group">
                  <label>📈 成绩范围：</label>
                  <select v-model="filterScoreRange" @change="applyFilters">
                    <option value="all">全部成绩</option>
                    <option value="excellent">优秀(90-100)</option>
                    <option value="good">良好(80-89)</option>
                    <option value="average">中等(70-79)</option>
                    <option value="poor">待提高(60-69)</option>
                    <option value="fail">不及格(<60)</option>
                  </select>
                </div>
              </div>
              
              <div class="action-buttons">
                <button @click="resetFilters" class="btn-reset">
                  🔄 重置筛选
                </button>
                <button @click="exportAnalysisData" class="btn-export">
                  📊 导出分析报告
                </button>
                <button @click="exportStudentData" class="btn-export">
                  👨‍🎓 导出学生数据
                </button>
                <button @click="generateTeachingPlan" class="btn-generate">
                  📋 生成教学计划
                </button>
              </div>
            </div>
          </div>
          
          <!-- 重点关注知识点 -->
          <div class="suggestion-card priority">
            <h4>🎯 需要重点讲解的知识点</h4>
            <div v-if="priorityKnowledgePoints.length > 0" class="priority-list">
              <div v-for="kp in priorityKnowledgePoints" :key="kp.knowledge_point" class="priority-item">
                <div class="priority-header">
                  <span class="knowledge-point">{{ kp.knowledge_point }}</span>
                  <span class="urgency-badge" :class="getUrgencyClass(kp.accuracy_rate)">{{ getUrgencyLevel(kp.accuracy_rate) }}</span>
                </div>
                <div class="priority-details">
                  <p><strong>问题分析：</strong>班级正确率仅{{ kp.accuracy_rate }}%，远低于预期标准</p>
                  <p><strong>建议措施：</strong></p>
                  <ul>
                    <li>安排专项练习，重点讲解该知识点的核心概念</li>
                    <li>分析常见错误选项，针对性纠正学生理解偏差</li>
                    <li>设计相关案例，帮助学生深入理解</li>
                    <li v-if="kp.accuracy_rate < 40">建议课后个别辅导成绩较差的学生</li>
                  </ul>
                </div>
              </div>
            </div>
            <div v-else class="no-issues">
              <p>🎉 所有知识点掌握情况良好，继续保持！</p>
            </div>
          </div>
          
          <!-- 个性化辅导建议 -->
          <div class="suggestion-card individual">
            <h4>👨‍🎓 个性化辅导建议</h4>
            <div v-if="dashboardData.need_help_students.length > 0" class="individual-suggestions">
              <div v-for="student in dashboardData.need_help_students" :key="student.student_name" class="student-suggestion">
                <div class="student-header">
                  <span class="student-name">{{ student.student_name }}</span>
                  <span class="score-badge low">{{ student.score }}分</span>
                </div>
                <div class="suggestion-content">
                  <p><strong>学习状况：</strong>当前成绩{{ student.score }}分，正确率{{ student.accuracy_rate }}%</p>
                  <p v-if="student.weak_knowledge_points.length > 0"><strong>薄弱环节：</strong>{{ student.weak_knowledge_points.join('、') }}</p>
                  <p><strong>辅导建议：</strong></p>
                  <ul>
                    <li>课后单独辅导，重点关注薄弱知识点</li>
                    <li>提供额外练习材料，巩固基础概念</li>
                    <li>建议与家长沟通，共同关注学生学习进度</li>
                    <li>安排学习伙伴，进行同伴互助学习</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 整体教学策略 -->
          <div class="suggestion-card strategy">
            <h4>📚 整体教学策略调整</h4>
            <div class="strategy-content">
              <div class="strategy-item">
                <h5>📊 基于数据的教学调整</h5>
                <ul>
                  <li>班级平均分{{ dashboardData.average_score }}分，{{ getClassLevelAdvice() }}</li>
                  <li>优秀率{{ excellentRate }}%，及格率{{ passRate }}%，{{ getPassRateAdvice() }}</li>
                  <li>共有{{ dashboardData.knowledge_point_analysis.length }}个知识点，其中{{ priorityKnowledgePoints.length }}个需要重点关注</li>
                </ul>
              </div>
              
              <div class="strategy-item">
                <h5>🎯 精准施教落地措施</h5>
                <ul>
                  <li><strong>分层教学：</strong>根据学生表现分组，优秀学生可进行拓展学习，后进学生加强基础训练</li>
                  <li><strong>错题回顾：</strong>定期组织错题讲解，重点分析高频错误选项</li>
                  <li><strong>数据跟踪：</strong>建立学生学习档案，持续跟踪进步情况</li>
                  <li><strong>家校合作：</strong>与家长分享学生学习数据，形成教育合力</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js'
import axios from 'axios'

// 注册Chart.js组件
Chart.register(...registerables)

export default {
  name: 'TeacherDashboard',
  data() {
    return {
      selectedClass: 1,
      selectedDate: new Date().toISOString().split('T')[0],
      currentView: 'overview',
      dashboardData: null,
      loading: false,
      error: null,
      scoreChart: null,
      trajectoryChart: null,
      selectedStudent: null,
      studentTrajectory: null,
      
      // 筛选相关数据
      filterTimeRange: 'all',
      filterClassRange: 'current',
      filterKnowledgePoint: 'all',
      filterScoreRange: 'all',
      customStartDate: '',
      customEndDate: '',
      selectedClasses: [],
      filteredData: null,
      
      viewModes: [
        { key: 'overview', label: '整体概览', icon: '📊' },
        { key: 'students', label: '学生分析', icon: '👨‍🎓' },
        { key: 'errors', label: '共性错题', icon: '🔍' },
        { key: 'suggestions', label: '教学建议', icon: '💡' }
      ]
    }
  },
  
  computed: {
    excellentRate() {
      if (!this.dashboardData || !this.dashboardData.score_distribution) return 0
      const excellent = this.dashboardData.score_distribution['90-100'] || 0
      return Math.round((excellent / this.dashboardData.total_students) * 100)
    },
    
    passRate() {
      if (!this.dashboardData || !this.dashboardData.score_distribution) return 0
      const total = this.dashboardData.total_students
      const failed = this.dashboardData.score_distribution['0-59'] || 0
      return Math.round(((total - failed) / total) * 100)
    },
    
    // 可用知识点列表
    availableKnowledgePoints() {
      if (!this.dashboardData || !this.dashboardData.knowledge_point_analysis) return []
      return this.dashboardData.knowledge_point_analysis.map(kp => kp.knowledge_point)
    },
    
    // 筛选后的优先知识点
    filteredPriorityKnowledgePoints() {
      if (!this.priorityKnowledgePoints) return []
      
      let filtered = [...this.priorityKnowledgePoints]
      
      // 按知识点筛选
      if (this.filterKnowledgePoint !== 'all') {
        if (this.filterKnowledgePoint === 'weak') {
          filtered = filtered.filter(kp => kp.accuracy_rate < 60)
        } else if (this.filterKnowledgePoint === 'priority') {
          filtered = filtered.filter(kp => kp.accuracy_rate < 70)
        } else {
          filtered = filtered.filter(kp => kp.knowledge_point === this.filterKnowledgePoint)
        }
      }
      
      return filtered
    },
    
    sortedKnowledgePoints() {
      if (!this.dashboardData || !this.dashboardData.knowledge_point_analysis) return []
      return [...this.dashboardData.knowledge_point_analysis].sort((a, b) => a.accuracy_rate - b.accuracy_rate)
    },
    
    priorityKnowledgePoints() {
      if (!this.dashboardData || !this.dashboardData.knowledge_point_analysis) return []
      return this.dashboardData.knowledge_point_analysis.filter(kp => kp.accuracy_rate < 70)
    }
  },
  
  mounted() {
    this.loadDashboardData()
  },
  
  methods: {
    // 日期格式化方法
    formatDate(dateString, defaultValue = '1900-01-01 00:00:00') {
      try {
        if (!dateString) {
          return '未知时间';
        }
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
          return defaultValue;
        }
        return date.toLocaleString('zh-CN');
      } catch (e) {
        console.warn('日期解析失败:', dateString, e);
        return defaultValue;
      }
    },

    async loadDashboardData() {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get(`/api/class-analysis/${this.selectedClass}`, {
          params: { date: this.selectedDate }
        })
        this.dashboardData = response.data
        
        // 延迟渲染图表，确保DOM已更新
        this.$nextTick(() => {
          if (this.currentView === 'overview') {
            this.renderScoreDistributionChart()
          }
        })
      } catch (error) {
        console.error('加载数据失败:', error)
        this.error = '加载教学数据失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },
    
    async fetchStudentTrajectory() {
      if (!this.selectedStudent) return;
      
      try {
        this.loading = true;
        const response = await axios.get(`/api/student-trajectory/${this.selectedClass}/${this.selectedStudent}`);
        this.studentTrajectory = response.data;
        
        // 创建学习轨迹图表
        this.createTrajectoryChart();
      } catch (error) {
        console.error('获取学生轨迹失败:', error);
        this.error = '获取学生学习轨迹失败';
      } finally {
        this.loading = false;
      }
    },
    
    createTrajectoryChart() {
       if (!this.studentTrajectory || !this.$refs.trajectoryChart) return;
       
       const ctx = this.$refs.trajectoryChart.getContext('2d');
       
       if (this.trajectoryChart) {
         this.trajectoryChart.destroy();
       }
       
       // 准备图表数据
       const trajectory = this.studentTrajectory.trajectory.slice().reverse(); // 按时间正序
       const labels = trajectory.map(record => `${record.date} ${record.time}`);
       const scores = trajectory.map(record => record.score);
       const accuracyRates = trajectory.map(record => 
         Math.round((record.correct_count / record.total_questions) * 100)
       );
       
       this.trajectoryChart = new Chart(ctx, {
         type: 'line',
         data: {
           labels: labels,
           datasets: [
             {
               label: '成绩分数',
               data: scores,
               borderColor: '#667eea',
               backgroundColor: 'rgba(102, 126, 234, 0.1)',
               tension: 0.4,
               fill: false,
               yAxisID: 'y'
             },
             {
               label: '正确率(%)',
               data: accuracyRates,
               borderColor: '#f093fb',
               backgroundColor: 'rgba(240, 147, 251, 0.1)',
               tension: 0.4,
               fill: false,
               yAxisID: 'y1'
             }
           ]
         },
         options: {
           responsive: true,
           maintainAspectRatio: false,
           interaction: {
             mode: 'index',
             intersect: false,
           },
           plugins: {
             legend: {
               display: true,
               position: 'top'
             },
             tooltip: {
               callbacks: {
                 title: function(context) {
                   return `答题时间: ${context[0].label}`;
                 },
                 afterBody: function(context) {
                   const index = context[0].dataIndex;
                   const record = trajectory[index];
                   return [
                     `正确题数: ${record.correct_count}/${record.total_questions}`,
                     `提交ID: ${record.submission_id}`
                   ];
                 }
               }
             }
           },
           scales: {
             x: {
               display: true,
               title: {
                 display: true,
                 text: '答题时间'
               },
               ticks: {
                 maxTicksLimit: 8
               }
             },
             y: {
               type: 'linear',
               display: true,
               position: 'left',
               title: {
                 display: true,
                 text: '成绩分数'
               },
               min: 0,
               max: 100
             },
             y1: {
               type: 'linear',
               display: true,
               position: 'right',
               title: {
                 display: true,
                 text: '正确率(%)'
               },
               min: 0,
               max: 100,
               grid: {
                 drawOnChartArea: false,
               },
             }
           }
         }
       });
     },
    
    renderScoreDistributionChart() {
      if (!this.dashboardData || !this.$refs.scoreDistributionChart) return
      
      const ctx = this.$refs.scoreDistributionChart.getContext('2d')
      
      if (this.scoreChart) {
        this.scoreChart.destroy()
      }
      
      const distribution = this.dashboardData.score_distribution
      
      this.scoreChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['90-100分', '80-89分', '70-79分', '60-69分', '0-59分'],
          datasets: [{
            label: '学生人数',
            data: [
              distribution['90-100'] || 0,
              distribution['80-89'] || 0,
              distribution['70-79'] || 0,
              distribution['60-69'] || 0,
              distribution['0-59'] || 0
            ],
            backgroundColor: [
              '#4CAF50',  // 优秀 - 绿色
              '#8BC34A',  // 良好 - 浅绿
              '#FFC107',  // 中等 - 黄色
              '#FF9800',  // 及格 - 橙色
              '#F44336'   // 不及格 - 红色
            ],
            borderColor: [
              '#388E3C',
              '#689F38',
              '#F57C00',
              '#E65100',
              '#D32F2F'
            ],
            borderWidth: 2,
            borderRadius: 8
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const total = context.dataset.data.reduce((a, b) => a + b, 0)
                  const percentage = total > 0 ? ((context.raw / total) * 100).toFixed(1) : 0
                  return `${context.raw}人 (${percentage}%)`
                }
              }
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                stepSize: 1
              }
            }
          }
        }
      })
    },
    
    getScoreTrendClass(score) {
      if (score >= 85) return 'trend-excellent'
      if (score >= 75) return 'trend-good'
      if (score >= 60) return 'trend-average'
      return 'trend-poor'
    },
    
    getScoreTrend(score) {
      if (score >= 85) return '表现优秀'
      if (score >= 75) return '表现良好'
      if (score >= 60) return '有待提高'
      return '需要关注'
    },
    
    getHeatmapClass(accuracy) {
      if (accuracy >= 90) return 'heat-excellent'
      if (accuracy >= 80) return 'heat-good'
      if (accuracy >= 70) return 'heat-average'
      if (accuracy >= 60) return 'heat-poor'
      return 'heat-critical'
    },
    
    getRankingClass(accuracy) {
      if (accuracy < 50) return 'ranking-critical'
      if (accuracy < 70) return 'ranking-warning'
      return 'ranking-normal'
    },
    
    getAccuracyClass(accuracy) {
      if (accuracy >= 80) return 'accuracy-good'
      if (accuracy >= 60) return 'accuracy-average'
      return 'accuracy-poor'
    },
    
    getUrgencyClass(accuracy) {
      if (accuracy < 40) return 'urgency-critical'
      if (accuracy < 60) return 'urgency-high'
      return 'urgency-medium'
    },
    
    getUrgencyLevel(accuracy) {
      if (accuracy < 40) return '紧急'
      if (accuracy < 60) return '重要'
      return '关注'
    },
    
    getClassLevelAdvice() {
      const score = this.dashboardData.average_score
      if (score >= 85) return '班级整体表现优秀，可适当增加拓展内容'
      if (score >= 75) return '班级整体表现良好，继续保持当前教学节奏'
      if (score >= 60) return '班级整体表现一般，建议加强基础知识讲解'
      return '班级整体表现较差，需要重新梳理教学内容，放慢教学进度'
    },
    
    getPassRateAdvice() {
      if (this.passRate >= 90) return '及格率很高，可以适当提高教学难度'
      if (this.passRate >= 80) return '及格率良好，保持当前教学策略'
      if (this.passRate >= 70) return '及格率一般，需要关注后进学生'
      return '及格率偏低，建议降低教学难度，加强基础训练'
    },
    
    calculateAverageAccuracy() {
      if (!this.studentTrajectory || !this.studentTrajectory.trajectory.length) return 0;
      const total = this.studentTrajectory.trajectory.reduce((sum, record) => {
        return sum + (record.correct_count / record.total_questions) * 100;
      }, 0);
      return Math.round(total / this.studentTrajectory.trajectory.length);
    },
    
    getKnowledgeScoreClass(score) {
      if (score >= 80) return 'score-excellent';
      if (score >= 60) return 'score-good';
      return 'score-poor';
    },
    
    getProgressColor(score) {
      if (score >= 80) return '#27ae60';
      if (score >= 60) return '#f39c12';
      return '#e74c3c';
    },
    
    getScoreClass(score) {
       if (score >= 90) return 'score-excellent';
       if (score >= 80) return 'score-good';
       if (score >= 60) return 'score-average';
       return 'score-poor';
     },
     
     // 错题分析相关方法
     getAverageErrorRate() {
       if (!this.dashboardData?.knowledge_point_analysis) return 0;
       const total = this.dashboardData.knowledge_point_analysis.reduce((sum, kp) => {
         return sum + (100 - kp.accuracy_rate);
       }, 0);
       return Math.round(total / this.dashboardData.knowledge_point_analysis.length);
     },
     
     getMostDifficultErrorRate() {
       if (!this.dashboardData?.knowledge_point_analysis) return 0;
       const mostDifficult = this.dashboardData.knowledge_point_analysis.reduce((min, kp) => {
         return kp.accuracy_rate < min.accuracy_rate ? kp : min;
       }, this.dashboardData.knowledge_point_analysis[0] || {accuracy_rate: 100});
       return 100 - mostDifficult.accuracy_rate;
     },
     
     getMostDifficultKnowledgePoint() {
       if (!this.dashboardData?.knowledge_point_analysis) return null;
       return this.dashboardData.knowledge_point_analysis.reduce((min, kp) => {
         return kp.accuracy_rate < min.accuracy_rate ? kp : min;
       }, this.dashboardData.knowledge_point_analysis[0]);
     },
     
     getRankClass(index) {
       if (index === 0) return 'rank-first';
       if (index === 1) return 'rank-second';
       if (index === 2) return 'rank-third';
       return 'rank-normal';
     },
     
     getErrorRateClass(errorRate) {
       if (errorRate >= 70) return 'error-critical';
       if (errorRate >= 50) return 'error-high';
       if (errorRate >= 30) return 'error-medium';
       return 'error-low';
     },
     
     getErrorProgressColor(errorRate) {
       if (errorRate >= 70) return '#e74c3c';
       if (errorRate >= 50) return '#f39c12';
       if (errorRate >= 30) return '#f1c40f';
       return '#27ae60';
     },
     
     // 筛选和导出功能方法
     applyFilters() {
       // 应用筛选条件，重新加载数据
       this.loadDashboardData();
     },
     
     resetFilters() {
       this.filterTimeRange = 'all';
       this.filterClassRange = 'current';
       this.filterKnowledgePoint = 'all';
       this.filterScoreRange = 'all';
       this.customStartDate = '';
       this.customEndDate = '';
       this.selectedClasses = [];
       this.applyFilters();
     },
     
     async exportAnalysisData() {
       try {
         // 询问导出格式
         const format = prompt('请选择导出格式:\n1. excel (Excel文件)\n2. csv (CSV文件)\n3. json (JSON文件)\n\n请输入格式名称:', 'excel');

         if (!format || !['excel', 'csv', 'json'].includes(format.toLowerCase())) {
           alert('❌ 请选择有效的导出格式 (excel/csv/json)');
           return;
         }

         if (format.toLowerCase() === 'json') {
           // 原有的JSON导出逻辑
           const exportData = {
             班级信息: {
               班级: `${this.selectedClass}班`,
               导出时间: new Date().toLocaleString(),
               数据日期: this.selectedDate
             },
             整体统计: {
               总人数: this.dashboardData.total_students,
               平均分: this.dashboardData.average_score,
               及格率: `${this.passRate}%`,
               优秀率: `${this.excellentRate}%`
             },
             知识点分析: this.dashboardData.knowledge_point_analysis.map(kp => ({
               知识点: kp.knowledge_point,
               正确率: `${kp.accuracy_rate}%`,
               答题次数: kp.total_attempts,
               正确次数: kp.correct_attempts
             })),
             学生表现: this.dashboardData.student_performance.map(student => ({
               姓名: student.student_name,
               分数: student.score,
               正确率: `${student.accuracy_rate}%`,
               薄弱知识点: student.weak_knowledge_points.join('、')
             }))
           };

           const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
           const url = URL.createObjectURL(blob);
           const a = document.createElement('a');
           a.href = url;
           a.download = `班级${this.selectedClass}_教学分析报告_${this.selectedDate}.json`;
           document.body.appendChild(a);
           a.click();
           document.body.removeChild(a);
           URL.revokeObjectURL(url);

           alert('📊 分析报告导出成功！');
         } else {
           // 使用后端API导出Excel或CSV
           const response = await axios.post('/api/teacher/dashboard/export', {
             class_id: this.selectedClass,
             format: format.toLowerCase()
           }, {
             responseType: 'blob'
           });

           // 获取文件名
           const contentDisposition = response.headers['content-disposition'];
           let filename = `班级${this.selectedClass}_教学分析报告_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.${format}`;
           if (contentDisposition) {
             const filenameMatch = contentDisposition.match(/filename=(.+)/);
             if (filenameMatch) {
               filename = filenameMatch[1];
             }
           }

           // 下载文件
           const url = window.URL.createObjectURL(new Blob([response.data]));
           const a = document.createElement('a');
           a.href = url;
           a.download = filename;
           document.body.appendChild(a);
           a.click();
           document.body.removeChild(a);
           window.URL.revokeObjectURL(url);

           alert('📊 分析报告导出成功！');
         }
       } catch (error) {
         console.error('导出失败:', error);
         alert('导出失败，请稍后重试');
       }
     },
     
     async exportStudentData() {
       try {
         let csvContent = '姓名,分数,正确率,薄弱知识点,建议措施\n';
         
         this.dashboardData.student_performance.forEach(student => {
           const weakPoints = student.weak_knowledge_points.join('；');
           const suggestions = this.getStudentSuggestions(student);
           csvContent += `${student.student_name},${student.score},${student.accuracy_rate}%,"${weakPoints}","${suggestions}"\n`;
         });
         
         const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
         const url = URL.createObjectURL(blob);
         const a = document.createElement('a');
         a.href = url;
         a.download = `班级${this.selectedClass}_学生数据_${this.selectedDate}.csv`;
         document.body.appendChild(a);
         a.click();
         document.body.removeChild(a);
         URL.revokeObjectURL(url);
         
         alert('👨‍🎓 学生数据导出成功！');
       } catch (error) {
         console.error('导出失败:', error);
         alert('导出失败，请稍后重试');
       }
     },
     
     getStudentSuggestions(student) {
       const suggestions = [];
       if (student.score < 60) {
         suggestions.push('需要重点关注，建议课后辅导');
       }
       if (student.accuracy_rate < 50) {
         suggestions.push('基础薄弱，需要加强练习');
       }
       if (student.weak_knowledge_points.length > 3) {
         suggestions.push('知识点掌握不均衡，建议系统复习');
       }
       return suggestions.length > 0 ? suggestions.join('；') : '继续保持，可适当拓展';
     },
     
     async generateTeachingPlan() {
       try {
         const plan = {
           班级: `${this.selectedClass}班`,
           生成时间: new Date().toLocaleString(),
           重点关注知识点: this.priorityKnowledgePoints.map(kp => ({
             知识点: kp.knowledge_point,
             正确率: `${kp.accuracy_rate}%`,
             教学建议: this.getKnowledgePointSuggestion(kp)
           })),
           分层教学安排: {
             优秀学生: `${this.dashboardData.excellent_students.length}人 - 可进行拓展学习`,
             中等学生: `${this.dashboardData.student_performance.filter(s => s.score >= 70 && s.score < 90).length}人 - 巩固提高`,
             待提高学生: `${this.dashboardData.need_help_students.length}人 - 重点辅导`
           },
           下周教学重点: this.getWeeklyFocus()
         };
         
         const blob = new Blob([JSON.stringify(plan, null, 2)], { type: 'application/json' });
         const url = URL.createObjectURL(blob);
         const a = document.createElement('a');
         a.href = url;
         a.download = `班级${this.selectedClass}_教学计划_${this.selectedDate}.json`;
         document.body.appendChild(a);
         a.click();
         document.body.removeChild(a);
         URL.revokeObjectURL(url);
         
         alert('📋 教学计划生成成功！');
       } catch (error) {
         console.error('生成失败:', error);
         alert('生成失败，请稍后重试');
       }
     },
     
     getWeeklyFocus() {
       const focus = [];
       if (this.priorityKnowledgePoints.length > 0) {
         focus.push(`重点讲解：${this.priorityKnowledgePoints[0].knowledge_point}`);
       }
       if (this.dashboardData.need_help_students.length > 0) {
         focus.push(`个别辅导：${this.dashboardData.need_help_students.slice(0, 3).map(s => s.student_name).join('、')}`);
       }
       focus.push('错题回顾：整理本周常见错误');
       return focus;
     }
  },
  
  watch: {
    currentView() {
      this.$nextTick(() => {
        if (this.currentView === 'overview' && this.dashboardData) {
          this.renderScoreDistributionChart()
        }
      })
    }
  },
  
  beforeUnmount() {
    if (this.scoreChart) {
      this.scoreChart.destroy()
    }
  }
}
</script>

<style scoped>
.teacher-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
}

.dashboard-header {
  text-align: center;
  margin-bottom: 40px;
  padding-bottom: 30px;
  border-bottom: 2px solid #f0f0f0;
}

.dashboard-header h1 {
  font-size: 2.5em;
  color: #2c3e50;
  margin-bottom: 10px;
  font-weight: bold;
}

.subtitle {
  font-size: 1.2em;
  color: #7f8c8d;
  margin-bottom: 30px;
  font-style: italic;
}

.controls-section {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  flex-wrap: wrap;
}

.class-selector, .date-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.class-selector label, .date-selector label {
  font-weight: bold;
  color: #34495e;
}

.class-selector select, .date-input {
  padding: 8px 15px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.class-selector select:focus, .date-input:focus {
  outline: none;
  border-color: #667eea;
}

.view-mode {
  display: flex;
  gap: 10px;
}

.view-btn {
  padding: 10px 20px;
  border: 2px solid #ddd;
  background: white;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: bold;
}

.view-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.view-btn.active {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border-color: transparent;
}

.loading {
  text-align: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  text-align: center;
  padding: 40px;
  color: #e74c3c;
}

/* 统计卡片样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20px;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card.primary { border-left: 5px solid #3498db; }
.stat-card.success { border-left: 5px solid #2ecc71; }
.stat-card.warning { border-left: 5px solid #f39c12; }
.stat-card.info { border-left: 5px solid #9b59b6; }

.stat-icon {
  font-size: 2.5em;
  opacity: 0.8;
}

.stat-number {
  font-size: 2.2em;
  font-weight: bold;
  color: #2c3e50;
}

.stat-label {
  font-size: 1.1em;
  color: #7f8c8d;
  margin: 5px 0;
}

.stat-trend {
  font-size: 0.9em;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: bold;
}

.trend-excellent { background: #d5f4e6; color: #27ae60; }
.trend-good { background: #fef9e7; color: #f39c12; }
.trend-average { background: #ebf3fd; color: #3498db; }
.trend-poor { background: #fadbd8; color: #e74c3c; }

/* 图表样式 */
.chart-section {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.chart-container {
  position: relative;
  height: 300px;
  margin-top: 20px;
}

/* 知识点热力图 */
.knowledge-heatmap {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.heatmap-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.heatmap-cell {
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  transition: transform 0.3s ease;
  cursor: pointer;
}

.heatmap-cell:hover {
  transform: scale(1.05);
}

.heat-excellent { background: #d5f4e6; color: #27ae60; }
.heat-good { background: #e8f5e8; color: #2ecc71; }
.heat-average { background: #fef9e7; color: #f39c12; }
.heat-poor { background: #fdeaea; color: #e67e22; }
.heat-critical { background: #fadbd8; color: #e74c3c; }

.cell-label {
  font-weight: bold;
  margin-bottom: 8px;
}

.cell-value {
  font-size: 1.2em;
  font-weight: bold;
}

/* 学生分析样式 */
.students-section {
  space-y: 30px;
}

.section-header {
  text-align: center;
  margin-bottom: 30px;
}

.section-header h3 {
  font-size: 1.8em;
  color: #2c3e50;
  margin-bottom: 10px;
}

.section-header p {
  color: #7f8c8d;
  font-size: 1.1em;
}

.performance-group {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.performance-group h4 {
  font-size: 1.4em;
  color: #2c3e50;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #ecf0f1;
}

.student-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.student-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: all 0.3s ease;
  position: relative;
}

.student-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.student-card.excellent {
  border-left: 4px solid #27ae60;
  background: linear-gradient(135deg, #d5f4e6 0%, #f8f9fa 100%);
}

.student-card.need-help {
  border-left: 4px solid #e74c3c;
  background: linear-gradient(135deg, #fadbd8 0%, #f8f9fa 100%);
}

.student-rank {
  background: linear-gradient(45deg, #f39c12, #e67e22);
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.1em;
}

.student-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.3em;
}

.student-avatar.warning {
  background: linear-gradient(45deg, #e74c3c, #c0392b);
}

.student-info {
  flex: 1;
}

.student-name {
  font-size: 1.2em;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 8px;
}

.student-metrics {
  display: flex;
  gap: 15px;
  margin-bottom: 8px;
}

.metric {
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 0.9em;
  font-weight: bold;
}

.metric.score {
  background: #e8f5e8;
  color: #27ae60;
}

.metric.score.low {
  background: #fadbd8;
  color: #e74c3c;
}

.metric.accuracy {
  background: #ebf3fd;
  color: #3498db;
}

.metric.accuracy.low {
  background: #fdeaea;
  color: #e67e22;
}

.submission-time {
  font-size: 0.9em;
  color: #7f8c8d;
}

.weak-points {
  margin-top: 10px;
}

.weak-point-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 5px;
}

.weak-point-tag {
  background: #fdeaea;
  color: #e74c3c;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8em;
  font-weight: bold;
}

.performance-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 0.8em;
  font-weight: bold;
}

.performance-badge.excellent {
  background: #d5f4e6;
  color: #27ae60;
}

.performance-badge.warning {
  background: #fadbd8;
  color: #e74c3c;
}

/* 错误分析样式 */
.errors-section {
  space-y: 30px;
}

.error-ranking {
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.ranking-list {
  space-y: 15px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.ranking-item:hover {
  transform: translateX(5px);
}

.ranking-item.ranking-critical {
  background: linear-gradient(135deg, #fadbd8 0%, #f8f9fa 100%);
  border-left: 4px solid #e74c3c;
}

.ranking-item.ranking-warning {
  background: linear-gradient(135deg, #fef9e7 0%, #f8f9fa 100%);
  border-left: 4px solid #f39c12;
}

.ranking-item.ranking-normal {
  background: linear-gradient(135deg, #e8f5e8 0%, #f8f9fa 100%);
  border-left: 4px solid #27ae60;
}

.ranking-number {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.2em;
}

.ranking-content {
  flex: 1;
}

.ranking-title {
  font-size: 1.2em;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 8px;
}

.ranking-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.ranking-stats span {
  font-size: 0.9em;
  color: #7f8c8d;
}

.error-rate {
  font-weight: bold;
  color: #e74c3c;
}

.common-errors {
  margin-top: 8px;
}

.error-option {
  background: #fdeaea;
  color: #e74c3c;
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 0.8em;
  margin-right: 5px;
  font-weight: bold;
}

.accuracy-indicator {
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: bold;
  font-size: 1.1em;
}

.accuracy-good {
  background: #d5f4e6;
  color: #27ae60;
}

.accuracy-average {
  background: #fef9e7;
  color: #f39c12;
}

.accuracy-poor {
  background: #fadbd8;
  color: #e74c3c;
}

/* 建议样式 */
.suggestions-section {
  space-y: 30px;
}

/* 筛选和导出控件样式 */
.filter-export-controls {
  background: #f8f9fa;
  border-radius: 15px;
  padding: 25px;
  margin: 25px 0;
  border: 2px solid #e9ecef;
}

.filter-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-group label {
  font-weight: bold;
  color: #495057;
  font-size: 0.9em;
}

.filter-group select {
  padding: 10px 12px;
  border: 2px solid #dee2e6;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  transition: all 0.3s ease;
}

.filter-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.custom-date-range {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 8px;
}

.custom-date-range input {
  padding: 8px 10px;
  border: 2px solid #dee2e6;
  border-radius: 6px;
  font-size: 13px;
}

.custom-date-range span {
  color: #6c757d;
  font-weight: bold;
}

.multiple-class-selector {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 8px;
  margin-top: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 10px;
  background: white;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.class-checkbox {
  display: flex;
  align-items: center;
  gap: 5px;
}

.class-checkbox input[type="checkbox"] {
  margin: 0;
}

.class-checkbox label {
  font-size: 0.85em;
  margin: 0;
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.btn-reset, .btn-export, .btn-generate {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-reset {
  background: #6c757d;
  color: white;
}

.btn-reset:hover {
  background: #5a6268;
  transform: translateY(-2px);
}

.btn-export {
  background: #28a745;
  color: white;
}

.btn-export:hover {
  background: #218838;
  transform: translateY(-2px);
}

.btn-generate {
  background: #667eea;
  color: white;
}

.btn-generate:hover {
  background: #5a6fd8;
  transform: translateY(-2px);
}

.suggestion-card {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.suggestion-card.priority {
  border-left: 5px solid #e74c3c;
}

.suggestion-card.individual {
  border-left: 5px solid #f39c12;
}

.suggestion-card.strategy {
  border-left: 5px solid #3498db;
}

.suggestion-card h4 {
  font-size: 1.4em;
  color: #2c3e50;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #ecf0f1;
}

.priority-list {
  space-y: 20px;
}

.priority-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border-left: 4px solid #e74c3c;
}

.priority-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.knowledge-point {
  font-size: 1.2em;
  font-weight: bold;
  color: #2c3e50;
}

.urgency-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 0.8em;
  font-weight: bold;
}

.urgency-critical {
  background: #fadbd8;
  color: #e74c3c;
}

.urgency-high {
  background: #fef9e7;
  color: #f39c12;
}

.urgency-medium {
  background: #ebf3fd;
  color: #3498db;
}

.priority-details ul {
  margin: 10px 0;
  padding-left: 20px;
}

.priority-details li {
  margin: 5px 0;
  color: #34495e;
}

.individual-suggestions {
  space-y: 20px;
}

.student-suggestion {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border-left: 4px solid #f39c12;
}

.student-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.student-header .student-name {
  font-size: 1.2em;
  font-weight: bold;
  color: #2c3e50;
}

.score-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-weight: bold;
}

.score-badge.low {
  background: #fadbd8;
  color: #e74c3c;
}

.suggestion-content ul {
  margin: 10px 0;
  padding-left: 20px;
}

.suggestion-content li {
  margin: 5px 0;
  color: #34495e;
}

.strategy-content {
  space-y: 25px;
}

.strategy-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
}

.strategy-item h5 {
  font-size: 1.2em;
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ecf0f1;
}

.no-data, .no-issues {
  text-align: center;
  padding: 40px;
  color: #7f8c8d;
  font-style: italic;
}

/* 学生轨迹分析样式 */
.student-selector-section {
  background: white;
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.student-selector-section h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.student-selector select {
  width: 100%;
  max-width: 400px;
  padding: 12px 15px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.student-selector select:focus {
  outline: none;
  border-color: #667eea;
}

.student-detail {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.student-overview {
  margin-bottom: 30px;
}

.overview-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.overview-card h4 {
  color: #2c3e50;
  margin-bottom: 15px;
  font-size: 1.3em;
}

.overview-card .stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-item .label {
  font-size: 0.9em;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.stat-item .value {
  font-size: 1.5em;
  font-weight: bold;
  color: #2c3e50;
}

.trajectory-chart {
  margin-bottom: 30px;
}

.trajectory-chart h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.knowledge-progress {
  margin-bottom: 30px;
}

.knowledge-progress h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.knowledge-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.knowledge-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.knowledge-name {
  font-weight: bold;
  color: #2c3e50;
}

.knowledge-score {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.9em;
  font-weight: bold;
}

.score-excellent {
  background: #d5f4e6;
  color: #27ae60;
}

.score-good {
  background: #fef9e7;
  color: #f39c12;
}

.score-average {
  background: #ebf3fd;
  color: #3498db;
}

.score-poor {
  background: #fadbd8;
  color: #e74c3c;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #ecf0f1;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.learning-history h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.history-table {
  overflow-x: auto;
}

.history-table table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-table th,
.history-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.history-table th {
  background: #f8f9fa;
  font-weight: bold;
  color: #2c3e50;
}

.history-table tr:hover {
  background: #f8f9fa;
}

.score-cell {
  font-weight: bold;
}

.student-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.student-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .controls-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .view-mode {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .student-grid {
    grid-template-columns: 1fr;
  }
  
  .ranking-stats {
    flex-direction: column;
    gap: 5px;
  }
  
  .priority-header, .student-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .knowledge-grid {
    grid-template-columns: 1fr;
  }
  
  .overview-card .stats-grid {
     grid-template-columns: 1fr;
   }
   
   .overview-cards {
     grid-template-columns: 1fr;
   }
   
   .kp-error-grid {
     grid-template-columns: 1fr;
   }
   
   .ranking-container {
     overflow-x: auto;
   }
 }
 
 /* 错题分析样式 */
 .error-overview-section {
   margin-bottom: 30px;
 }
 
 .overview-cards {
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
   gap: 20px;
   margin-bottom: 30px;
 }
 
 .stat-card {
   background: white;
   border-radius: 15px;
   padding: 25px;
   box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
   display: flex;
   align-items: flex-start;
   gap: 15px;
 }
 
 .card-icon {
   font-size: 2em;
   flex-shrink: 0;
 }
 
 .card-content {
   flex: 1;
 }
 
 .card-content h4 {
   color: #2c3e50;
   margin-bottom: 15px;
   font-size: 1.2em;
 }
 
 .summary-stats {
   display: flex;
   flex-direction: column;
   gap: 10px;
 }
 
 .summary-item {
   display: flex;
   justify-content: space-between;
   align-items: center;
 }
 
 .summary-item .label {
   color: #7f8c8d;
   font-size: 0.9em;
 }
 
 .summary-item .value {
   font-weight: bold;
   color: #2c3e50;
   font-size: 1.1em;
 }
 
 .difficult-question {
   margin-top: 10px;
 }
 
 .question-content {
   color: #2c3e50;
   font-weight: 500;
   margin-bottom: 8px;
   line-height: 1.4;
 }
 
 .question-meta {
   display: flex;
   gap: 10px;
   align-items: center;
 }
 
 .error-rate {
   background: #fadbd8;
   color: #e74c3c;
   padding: 4px 8px;
   border-radius: 12px;
   font-size: 0.9em;
   font-weight: bold;
 }
 
 .kp-info {
   margin-top: 10px;
 }
 
 .kp-name {
   color: #2c3e50;
   font-weight: 500;
   margin-bottom: 8px;
 }
 
 .kp-stats {
   display: flex;
   flex-direction: column;
   gap: 5px;
 }
 
 .error-count {
   color: #7f8c8d;
   font-size: 0.9em;
 }
 
 /* 排行榜样式 */
 .ranking-container {
   background: white;
   border-radius: 15px;
   overflow: hidden;
   box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
 }
 
 .ranking-header {
   display: grid;
   grid-template-columns: 60px 2fr 1fr 1fr 1.5fr;
   gap: 15px;
   padding: 20px;
   background: #f8f9fa;
   font-weight: bold;
   color: #2c3e50;
   border-bottom: 2px solid #ecf0f1;
 }
 
 .ranking-list {
   max-height: 600px;
   overflow-y: auto;
 }
 
 .ranking-item {
   display: grid;
   grid-template-columns: 60px 2fr 1fr 1fr 1.5fr;
   gap: 15px;
   padding: 20px;
   border-bottom: 1px solid #ecf0f1;
   align-items: center;
   transition: background-color 0.3s ease;
 }
 
 .ranking-item:hover {
   background: #f8f9fa;
 }
 
 .rank-badge {
   width: 40px;
   height: 40px;
   border-radius: 50%;
   display: flex;
   align-items: center;
   justify-content: center;
   font-weight: bold;
   color: white;
 }
 
 .rank-first {
   background: linear-gradient(135deg, #ffd700, #ffed4e);
 }
 
 .rank-second {
   background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
 }
 
 .rank-third {
   background: linear-gradient(135deg, #cd7f32, #daa520);
 }
 
 .rank-normal {
   background: #95a5a6;
 }
 
 .question-text {
   color: #2c3e50;
   line-height: 1.4;
   margin-bottom: 5px;
 }
 
 .correct-answer {
   color: #27ae60;
   font-size: 0.9em;
   font-weight: 500;
 }
 
 .knowledge-point-tag {
   background: #e3f2fd;
   color: #1976d2;
   padding: 6px 12px;
   border-radius: 20px;
   font-size: 0.9em;
   font-weight: 500;
   text-align: center;
 }
 
 .error-statistics {
   text-align: center;
 }
 
 .error-rate-display {
   font-size: 1.2em;
   font-weight: bold;
   padding: 8px 12px;
   border-radius: 8px;
   margin-bottom: 5px;
 }
 
 .error-critical {
   background: #fadbd8;
   color: #e74c3c;
 }
 
 .error-high {
   background: #fef9e7;
   color: #f39c12;
 }
 
 .error-medium {
   background: #fff3cd;
   color: #856404;
 }
 
 .error-low {
   background: #d5f4e6;
   color: #27ae60;
 }
 
 .error-details {
   color: #7f8c8d;
   font-size: 0.9em;
 }
 
 .common-wrong-answers {
   display: flex;
   flex-direction: column;
   gap: 5px;
 }
 
 .wrong-answer-item {
   display: flex;
   justify-content: space-between;
   align-items: center;
   background: #f8f9fa;
   padding: 6px 10px;
   border-radius: 6px;
   font-size: 0.9em;
 }
 
 .wrong-answer-item .answer {
   font-weight: 500;
   color: #e74c3c;
 }
 
 .wrong-answer-item .count {
   color: #7f8c8d;
 }
 
 /* 知识点错误分析样式 */
 .knowledge-error-section {
   margin-top: 30px;
 }
 
 .knowledge-error-section h4 {
   color: #2c3e50;
   margin-bottom: 20px;
 }
 
 .kp-error-grid {
   display: grid;
   grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
   gap: 20px;
 }
 
 .kp-error-card {
   background: white;
   border-radius: 12px;
   padding: 20px;
   box-shadow: 0 3px 15px rgba(0, 0, 0, 0.05);
   transition: transform 0.3s ease, box-shadow 0.3s ease;
 }
 
 .kp-error-card:hover {
   transform: translateY(-3px);
   box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
 }
 
 .kp-header {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-bottom: 15px;
 }
 
 .kp-header h5 {
   color: #2c3e50;
   margin: 0;
   font-size: 1.1em;
 }
 
 .kp-error-rate {
   padding: 6px 10px;
   border-radius: 15px;
   font-size: 0.9em;
   font-weight: bold;
 }
 
 .kp-stats {
   margin-bottom: 15px;
 }
 
 .stat-row {
   display: flex;
   justify-content: space-between;
   margin-bottom: 8px;
 }
 
 .stat-row .label {
   color: #7f8c8d;
   font-size: 0.9em;
 }
 
 .stat-row .value {
   color: #2c3e50;
   font-weight: 500;
 }

@media (max-width: 480px) {
  .container {
    margin: 10px;
    padding: 15px;
  }
  
  .dashboard-header h1 {
    font-size: 2em;
  }
  
  .subtitle {
    font-size: 1em;
  }
  
  .heatmap-grid {
    grid-template-columns: 1fr;
  }
  
  .student-card {
    flex-direction: column;
    text-align: center;
  }
  
  .ranking-item {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
}
</style>